import { ConfigProvider, Modal, Form, Flex, notification, Button, AutoComplete, Upload, Checkbox, Select, Space, Input, Row, Col } from "antd";
import { FC, useState, useEffect } from "react";
import { Link } from "react-router-dom";
import { useRecoilState, useRecoilValue } from "recoil";
import { ConfigProvider as AuthProvider, ConfigState } from "../../hooks/root/atom";
import { getConfigInfo } from "../../hooks/root/selector";
import { useTranslation } from 'react-i18next';
import { CodeIds, FState, CertConf } from "./data";
import { uploadFile, uploadImage } from "../../hooks/upload/api";

import style from "./modal.module.scss";
import "./modal.style.scss";

interface conf {
  [key: string]: string
}

const Shiming: FC = () => {
  const [state, setRootState] = useRecoilState<ConfigState>(AuthProvider);
  const { options: { basic = {} } } = useRecoilValue(getConfigInfo);
  const [api, contextHolder] = notification.useNotification()
  const [form] = Form.useForm()
  const [t] = useTranslation("translation", {
    keyPrefix: "root"
  });
  const [forms, setForm] = useState<FState>({
    state: "1"
  });
  const [config, setConfig] = useState<conf>({})
  useEffect(() => {
    const keys: any = CertConf["1"];
    setConfig(keys)
    setForm({
      state: '1',
      files: {}
    })
  }, []);
  if (state.isAuth) {
    const submit = () => {
      form.validateFields()
        .then()
        .catch((err) => {
          api.error({
            message: t("hint"),
            description: t("errors.form"),
            placement: "topRight",
            showProgress: true,
            pauseOnHover: true
          })
          console.log(err)
        })
    };

    const onType = () => {
      const val = form.getFieldsValue();
      if (val.state !== forms.state) {
        const keys = CertConf[val.state];
        setConfig(keys);
        setForm(val);
      }
    }
    const onCode = () => {
      form.validateFields(["mail"]).then((res) => { }).catch(() => { })
    }

    const normFile = (e: any) => {
      if (Array.isArray(e)) {
        return e
      }
      return e && e.fileList ? e.fileList : e
    }

    const postFile = async (file: any, key: string) => {
      uploadFile({
        state: forms.state,
        file: file
      }).then(res => {
        console.log(res)
      })
    }

    const postImage = async (file: any, key: string) => {
      uploadImage({
        state: forms.state,
        file: file
      }).then(res => {
        const files = form.getFieldValue('files')
        file.url = `${basic.origin}${res.data}`
        file.thumbUrl = `${basic.origin}${res.data}`
        files[key] = [file]
        form.setFieldValue('files', files)
      })
    }
    const exit = () => {
      const opts = {
        ...state,
        isAuth: false
      }
      setRootState(opts)
    }
    const files: any = forms.files || {};
    return (<ConfigProvider>
      {contextHolder}
      <Modal
        classNames={{
          header: style.modal_header,
          body: style.modal_body
        }}
        wrapClassName="modal"
        centered
        width={600}
        title="实名提交"
        footer={<Flex justify="space-between" align="center" className={style.modal_footer} gap={25}>
          <Button className={style.modal_btn} type="primary" size="large" onClick={exit}>取消提交</Button>
          <Button className={style.modal_btn} type="primary" size="large" onClick={submit}>实名提交</Button>
        </Flex>}
        open={state.isAuth}>
        <Form form={form} requiredMark={false} layout="vertical" className={style.modal_form}>
          <Form.Item name="name" rules={[
            { required: true, message: "请输入称呼" },
            { min: 2, max: 36, message: "用户名最少2位，最多36位" },
            { pattern: /^[A-Za-z\u4e00-\u9fa5]/, message: "称呼只能汉字或者字母开头" }
          ]}>
            <AutoComplete
              // options={userList}
              placeholder="请输入称呼"
              size="large"
              backfill />
          </Form.Item>
          <Form.Item>
            <Space.Compact block>
              <Form.Item name={"state"} noStyle initialValue={"1"}>
                <Select size="large" className={style.modal_type} options={CodeIds} onChange={onType}></Select>
              </Form.Item>
              <Form.Item name={"code"} noStyle rules={[
                { required: true, message: config.msg }
              ]}>
                <Input size="large" className={style.modal_inpTxt} />
              </Form.Item>
            </Space.Compact>
          </Form.Item>
          {
            /^[2]$/.test(forms.state) ? <Form.Item label={config.title}>
              <Flex gap={15} justify="flex-start">
                <Form.Item name={["files", "zhengjian_3"]} valuePropName="fileList" getValueFromEvent={normFile} noStyle rules={[
                  { required: true, message: config.zhizhao_h },
                ]}>
                  <Upload
                    listType="picture-card"
                    className={`avatar-uploader modal_code`}
                    withCredentials
                    beforeUpload={(file) => {
                      postImage(file, "zhengjian_3")
                      return false
                    }}
                    onChange={() => setForm(form.getFieldsValue(true))}
                    maxCount={1}>{files.zhengjian_3 && files.zhengjian_3.length > 0 ? "" : config.zhengjian_3}</Upload>
                </Form.Item>
                <Form.Item name={["files", "zhengjian_4"]} valuePropName="fileList" getValueFromEvent={normFile} noStyle rules={[
                  { required: true, message: config.shouquan_h },
                ]}>
                  <Upload
                    className={`avatar-uploader modal_code`}
                    listType="picture-card"
                    withCredentials
                    beforeUpload={(file) => {
                      postFile(file, "zhengjian_4")
                      return false
                    }}
                    onChange={() => {
                      setForm(form.getFieldsValue(true))
                      console.log(files, config)
                    }}
                    maxCount={1}>{files.zhengjian_4 && files.zhengjian_4.length > 0 ? "" : config.zhengjian_4}</Upload>
                </Form.Item>
                <Row justify="center" align="middle">
                  <Col style={{ textAlign: 'center' }}>
                    请您先下载授权书模板，签写相应信息，盖企业公章上传
                  </Col>
                  <Col>
                    <Link target="_blank" to={`${basic.origin}/download/word?filename=授权书模板`}><Button type="primary">授权书模板</Button></Link>
                  </Col>
                </Row>
              </Flex>
            </Form.Item> : null
          }
          {
            /^[1-5]$/.test(forms.state) ? <Form.Item label={config.user}>
              <Flex gap={15}>
                <Form.Item name={["files", "zhengjian_1"]} valuePropName="fileList" getValueFromEvent={normFile} noStyle rules={[
                  { required: true, message: config.zhengjian_1 },
                ]}>
                  <Upload
                    listType="picture-card"
                    className={`avatar-uploader modal_code`}
                    withCredentials
                    beforeUpload={(file) => {
                      postImage(file, "zhengjian_1")
                      return false
                    }}
                    onChange={() => setForm(form.getFieldsValue(true))}
                    maxCount={1}>{files.zhengjian_1 && files.zhengjian_1.length > 0 ? "" : config.zhengjian_1}</Upload>
                </Form.Item>
                <Form.Item name={["files", "zhengjian_2 "]} valuePropName="fileList" getValueFromEvent={normFile} noStyle rules={[
                  { required: true, message: config.zhengjian_2 },
                ]}>
                  <Upload
                    listType="picture-card"
                    className={`avatar-uploader modal_code`}
                    withCredentials
                    beforeUpload={(file) => {
                      postImage(file, "zhengjian_2")
                      return false
                    }}
                    onChange={() => setForm(form.getFieldsValue(true))}
                    maxCount={1}>{files.zhengjian_2 && files.zhengjian_2.length > 0 ? "" : config.zhengjian_2}</Upload>
                </Form.Item>
              </Flex>
            </Form.Item> : null
          }
          {
            /^[6]$/.test(forms.state) ? <Form.Item>
              <Flex gap={15}>
                <Form.Item name={["files", "zhengjian_1"]} valuePropName="fileList" getValueFromEvent={normFile} noStyle rules={[
                  { required: true, message: config.zhengjian_1 },
                ]}>
                  <Upload
                    listType="picture-card"
                    className={`avatar-uploader modal_code`}
                    withCredentials
                    beforeUpload={(file) => {
                      postImage(file, "zhengjian_1")
                      return false
                    }}
                    onChange={() => setForm(form.getFieldsValue(true))}
                    maxCount={1}>{files.zhengjian_1 && files.zhengjian_1.length > 0 ? "" : config.zhengjian_1}</Upload>
                </Form.Item>
              </Flex>
            </Form.Item> : null
          }
          <Form.Item name="mail" rules={[
            { required: true, message: "请输入您的电子邮箱" },
          ]}>
            <AutoComplete
              // options={userList}
              placeholder="请输入您的电子邮箱"
              size="large"
              backfill />
          </Form.Item>
          <Form.Item name="y_code" style={{ marginBottom: 5 }} rules={[
            { required: true, message: "请输入验证码" },
            { min: 8, max: 8, message: "验证码为8位数字" }
          ]}>
            <Space.Compact block>
              <Form.Item noStyle name="y_code">
                <Input size="large" />
              </Form.Item>
              <Button className={style.modal_y} type="primary" size="large" onClick={onCode}>验证码</Button>
            </Space.Compact>
          </Form.Item>
          <Form.Item name="checked" valuePropName="checked" rules={[
            () => ({
              validator(_, value) {
                return value ? Promise.resolve() : Promise.reject(new Error("请勾选服务协议"))
              }
            })
          ]}>
            <Flex justify="start" align="center" gap={8}>
              <Checkbox></Checkbox>
              <Link to={"#"}>同意并遵守《服务与隐私协议》</Link>
            </Flex>
          </Form.Item>
        </Form>
      </Modal>
    </ConfigProvider>)
  } else {
    return null
  }
}

export default Shiming